package personal.wang.manager;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import personal.wang.config.DataMockYamlReader;
import personal.wang.constant.ConstantVar;
import personal.wang.domain.HeartbeatBean;
import personal.wang.enm.MessageType;
import personal.wang.handler.WorkerHandler;
import personal.wang.message.*;
import personal.wang.util.SystemInfoUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;

/**
 * @className: NetworkManager
 * @Description:
 * @Author: wangyifei
 * @Date: 2025/2/26 17:47
 */
public class NetworkManager {
    private static final Logger logger = LoggerFactory.getLogger(NetworkManager.class);
    private static Bootstrap bootstrap = new Bootstrap();
    private static NioEventLoopGroup group = new NioEventLoopGroup();
    private static Channel client ;
    static {
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MessageEncoder());
                        ch.pipeline().addLast(new MessageDecoder());
                        ch.pipeline().addLast(new WorkerHandler());
                    }
                }).option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(10 * 1024))
                .option(ChannelOption.SO_RCVBUF, 10 * 1024);
    }
    public static Channel getClient(){
        return client ;
    }

    public static void reconnectBoss(String ip, String port) {
        logger.info("ip: {} , port: {}" , ip , port);
        try {
            if(Objects.nonNull(client)){
                client.disconnect();
                client = null ;
            }
            ChannelFuture connect = bootstrap.connect(ip , Integer.parseInt(port));
            client = connect
                    .sync()
                    .channel();
        } catch (InterruptedException e) {
            logger.error("{}" , e.getMessage());
        }

    }
}
